package com.huang.community.controller;

import com.huang.community.common.CommunityConstant;
import com.huang.community.common.annotation.MaxImage;
import com.huang.community.model.NewPage;
import com.huang.community.pojo.Comment;
import com.huang.community.pojo.DiscussPost;
import com.huang.community.service.*;
import com.huang.community.common.annotation.LoginRequired;
import com.huang.community.pojo.User;
import com.huang.community.util.CommunityUtil;
import com.huang.community.util.HostHolder;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 * @author TianTian
 * @date 2022/4/28 22:09
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {
    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LikeService likeService;
    @Autowired
    private FollowService followService;
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private CommentService commentService;

    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String headerBucketName;

    @Value("${qiniu.prefix}")
    private String headerBucketUrl;
    //用户设置
    @LoginRequired
    @RequestMapping(path = "/setting", method = RequestMethod.GET)
    public String getSettingPage(Model model) {
        // 上传文件名称
        String fileName = CommunityUtil.generateUUID();
        // 设置响应信息
        StringMap policy = new StringMap();
        policy.put("returnBody", CommunityUtil.getJSONString(0));
        // 生成上传凭证
        Auth auth = Auth.create(accessKey, secretKey);
        String uploadToken = auth.uploadToken(headerBucketName, fileName, 3600, policy);

        model.addAttribute("uploadToken", uploadToken);
        model.addAttribute("fileName", fileName);

        return "/site/setting";
    }

    // 更新头像路径 七牛云
    @RequestMapping(path = "/header/url", method = RequestMethod.POST)
    @ResponseBody
    public String updateHeaderUrl(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return CommunityUtil.getJSONString(1, "文件名不能为空!");
        }
        String url = "http://"+headerBucketUrl + "/" + fileName;
        userService.updateHeader(hostHolder.getUser().getId(), url);
        return CommunityUtil.getJSONString(0);
    }

//    @LoginRequired
//    @RequestMapping(path = "/setting", method = RequestMethod.GET)
//    public String getSettingPage() {
//        return "/site/setting";
//    }
//
//
//    @LoginRequired
//    @RequestMapping(path = "/upload", method = RequestMethod.POST)
//    public String uploadHeader(MultipartFile headerImage, Model model) {
//        if (headerImage == null) {
//            model.addAttribute("error", "您还没有选择图片!");
//            return "/site/setting";
//        }
//
//        String fileName = headerImage.getOriginalFilename();
//        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
//        if (StringUtils.isBlank(suffix)) {
//            model.addAttribute("error", "文件的格式不正确!");
//            return "/site/setting";
//        }
//        log.debug(suffix);
//        String Stander="png,jpg";
//        if(!Stander.contains(suffix)){
//            model.addAttribute("error", "文件的格式不正确!");
//            return "/site/setting";
//
//        }
//
//        // 生成随机文件名
//        fileName = CommunityUtil.generateUUID() + suffix;
//        // 确定文件存放的路径
//        File dest = new File(uploadPath + "/" + fileName);
//        try {
//            // 存储文件
//            headerImage.transferTo(dest);
//        } catch (IOException e) {
//            log.error("上传文件失败: " + e.getMessage());
//            throw new RuntimeException("上传文件失败,服务器发生异常!", e);
//        }
//
//        // 更新当前用户的头像的路径(web访问路径)
//        // http://localhost:8080/community/user/header/xxx.png
//        User user = hostHolder.getUser();
//        String headerUrl = domain + contextPath + "/user/header/" + fileName;
//        //更新数据库
//        userService.updateHeader(user.getId(), headerUrl);
//        user.setHeaderUrl(headerUrl);
//        //更新Threadlocal
//        hostHolder.setUser(user);
//        return "redirect:/index";
//    }

//    @RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)
//    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
////        // 服务器存放路径
//        fileName = uploadPath + "/" + fileName;
//
//        // 文件后缀 注意要。的下一位 不然变成imgae/.png
//        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
//        // 响应图片
//        response.setContentType("image/" + suffix);
//        try (
//                FileInputStream fis = new FileInputStream(fileName);
//                OutputStream os = response.getOutputStream();
//        ) {
//            byte[] buffer = new byte[1024];
//            int b = 0;
//            while ((b = fis.read(buffer)) != -1) {
//                os.write(buffer, 0, b);
//            }
//        } catch (IOException e) {
//            log.error("读取头像失败: " + e.getMessage());
//        }
//    }

    //修改密码
    @RequestMapping("/changePassword")
    public String changePassword(Model model,String newPassword,String oldPassword,String confirmPassword){
        Map<String, Object> map = userService.updatePassword(oldPassword, newPassword, confirmPassword);
        model.addAttribute("oldMsg",map.get("oldMsg"));
        model.addAttribute("newMsg",map.get("newMsg"));
        model.addAttribute("confirmMsg",map.get("confirmMsg"));
        if ((boolean)map.get("flag")){
         return "/site/setting";
        }
        return "forward:/logout";

    }
    // 个人主页
    @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }

        // 用户
        model.addAttribute("user", user);
        // 点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);

        // 关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);
        // 粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);
        // 是否已关注
        boolean hasFollowed = false;
        if (hostHolder.getUser() != null) {
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);

        return "/site/profile";
    }
    // 我的帖子
    @RequestMapping("/mypost/{userId}")
    public String userComment(@PathVariable("userId") Integer userId, Model model, NewPage page){
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }
        HashMap<String, Object> hm = discussPostService.findDiscussPosts(userId, page.getCurrent(), page.getLimit(),0);
        page.setRows((int)hm.get("total"));
        page.setPath("/user/mypost/"+userId);
        List<DiscussPost> list = (List<DiscussPost>) hm.get("discussPosts");
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (list != null) {
            for (DiscussPost post : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("post", post);
                //新增加的方法 点赞数量
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount", likeCount);
                discussPosts.add(map);
            }
        }
        model.addAttribute("postCount",discussPostService.discussPostCount(userId));
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("user",user);
        return "/site/my-post";
    }
    //我的回复
    @RequestMapping(path = "/mycomment/{userId}", method = RequestMethod.GET)
    public String toMyReply(@PathVariable("userId") int userId,Model model, NewPage page,
                            @RequestParam(name = "infoMode", defaultValue = "2") int infoMode) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }
        model.addAttribute("user", user);

        // 设置分页信息
        page.setLimit(5);
        page.setRows(commentService.findCommentCountByUserId(user.getId()));
        page.setPath("/user/mycomment/"+userId);

        // 获取用户所有评论 (而不是回复,所以在 sql 里加一个条件 entity_type = 1)
        List<Comment> comments = commentService.findCommentOnlyComByuid(user.getId(),page.getCurrent(), page.getLimit());
        List<Map<String, Object>> list = new ArrayList<>();
        if (comments != null) {
            for (Comment comment : comments) {
                Map<String, Object> map = new HashMap<>();
                map.put("comment", comment);
                // 根据实体 id 查询对应的帖子标题
                String discussPostTitle = discussPostService.getDiscussPostById(comment.getEntityId()).getTitle();
                map.put("discussPostTitle", discussPostTitle);
                list.add(map);
            }
            model.addAttribute("comments", list);
        }
        // 回复的数量
        int commentCount = commentService.findCommentCountByUserId(user.getId());
        model.addAttribute("commentCount", commentCount);
        model.addAttribute("infoMode", infoMode);
        return "site/my-comment";
    }
}
